package com.example.xd.defaultcall;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.telecom.TelecomManager;
import android.text.TextUtils;

import java.lang.reflect.Method;

/**
 * @auther XuDan on 2020/6/3.
 */
public class TelecomManagerUitls {

    private final TelecomManager mTelecom;
    private String packageName;

    private TelecomManagerUitls(Context context) {
        mTelecom = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
        packageName = context.getPackageName();

    }

    public static TelecomManagerUitls getInstance(Context context) {
        return new TelecomManagerUitls(context);
    }

    public boolean isDefaultCall() {
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            String dialerPackage = mTelecom.getDefaultDialerPackage();
            if (!TextUtils.isEmpty(dialerPackage) && packageName.equals(dialerPackage)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    //使用反射
    public void setDefaultCall() {
        Class clazz = mTelecom.getClass();
        try {
            Method m = clazz.getDeclaredMethod("setDefaultDialer");
            m.setAccessible(true);
            m.invoke(clazz, packageName);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @SuppressLint("MissingPermission")
    public void call(String num) {
        Uri uri = Uri.fromParts("tel", num, null);
        Bundle extras = new Bundle();
        extras.putBoolean(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, true);
        mTelecom.placeCall(uri, extras);
    }


}
